<?php

/**
 * Swige Application Bootstrap
 * 
 * @version 2.0
 * @license MIT
 */

declare(strict_types=1);

namespace Bootstrap;


use DI\ContainerBuilder;
use Dotenv\Dotenv;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Monolog\Processor\MemoryUsageProcessor;
use Monolog\Processor\ProcessIdProcessor;
use Monolog\Processor\PsrLogMessageProcessor;
use Psr\Container\ContainerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Application;

final class App
{
    /**
     * 主构建方法
     *
     * @return ContainerInterface
     */
    public static function build(): ContainerInterface
    {
        self::loadEnvironment();     // 1. 加载环境配置
        return self::buildContainer(); // 2. 构建容器
    }
    /**
     * 环境加载
     *
     * @return void
     */
    private static function loadEnvironment(): void
    {
        try {
            $dotenv = Dotenv::createImmutable(APP_BASE_PATH);  // 加载 .env 文件
            $dotenv->load(); // 安全加载（不抛异常） $dotenv->safeLoad();
            date_default_timezone_set($_ENV['APP_TIMEZONE'] ?? 'Asia/Shanghai');

            // 根据调试模式设置错误报告
            if (self::isDebugEnabled()) {
                error_reporting(E_ALL);
                ini_set('display_errors', '1'); // 开发模式：显示所有错误
            } else {
                error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT);  // 生产模式：隐藏某些错误
                ini_set('display_errors', '0');
            }
        } catch (\Throwable $e) {
            self::terminate('Environment Error: ' . $e->getMessage());
        }
    }
    /**
     * 容器构建
     *
     * @return ContainerInterface
     */
    private static function buildContainer(): ContainerInterface
    {
        try {
            $builder = new ContainerBuilder();
            $builder->addDefinitions(base_path('config/di.php'));
            $builder->useAutowiring(true);
            $container = $builder->build();  // 构建 PHP-DI 容器
            return $container;
        } catch (\Throwable $e) {
            self::terminate('Container Build Failed: ' . $e->getMessage());
        }
    }

    public static function getContainer(): ContainerInterface
    {
        return self::$container ?? self::build();
    }

    /**
     * 辅助方法
     *
     * @return boolean
     */
    private static function isDebugEnabled(): bool
    {
        return filter_var($_ENV['APP_DEBUG'] ?? false, FILTER_VALIDATE_BOOLEAN);
    }

    private static function terminate(string $message): never
    {
        fwrite(STDERR, "⛔ $message\n");
        exit(1);
    }
}
